import Vue from "vue";
import iView from "view-design";
import axios from "axios";
import vueAxios from "vue-axios";

Vue.use(vueAxios, axios);

export default {
  init (router, store, restoreConfig) {
    this.router = router;
    this.store = store;
    this.restoreConfig = restoreConfig;

    this.restore();

    /**
     * axios请求拦截处理
     */
    axios.interceptors.request.use(config => {
      if (!config.hideTip) {
        let spinText = config.spinText || "正在处理中...";

        iView.Spin.show({
          render: h => {
            return h("div", [
              h("Icon", {
                class: "spin-icon-load",
                props: { type: "ios-loading", size: 18 }
              }),
              h("div", spinText)
            ]);
          }
        });
      }

      if (this.restoreConfig.enable) {
        this.restoreOAuth();

        // 在请求头中加入凭证信息
        config.headers["Authorization"] = store.state.oauth.authorization;
      }

      return config;
    });

    /**
     * axios响应拦截处理。
     */
    axios.interceptors.response.use(
      response => {
        if (!response.config.hideTip) {
          iView.Spin.hide();
        }

        if (response.data.IsSuccess != undefined && !response.data.IsSuccess) {
          if (!response.config.hideTip) {
            iView.Notice.error({
              title: "错误！",
              desc: response.data.ErrorMessage,
              duration: 10
            });
          }
        }

        return response.data;
      },
      error => {
        iView.Spin.hide();

        if (error.response) {
          switch (error.response.status) {
            case 500:
              iView.Message.error(`服务器异常:${error.response.data}`);
              break;
            case 504:
              iView.Message.error("网络错误");
              break;

            // 401 清除token信息并跳转到登录页面
            case 401:
            case 403:
              iView.Message.error({
                content: "您没有权限访问该页面！",
                duration: 2
              });

              router.push(this.restoreConfig.logOnUrl);

              break;
            default:
              iView.Message.error("请求错误！");
          }
        } else {
          iView.Message.error("网络错误！");
        }

        return Promise.reject(error);
      }
    );
  },
  restoreOAuth () {
    if (!this.restoreConfig.enable) {
      return;
    }

    let oauth = JSON.parse(sessionStorage.getItem('oauth'));

    if (oauth) {
      const self = this;

      if (self.store.getters.isLogged()) {
        self.store.commit('setAccessToken', oauth);
      } else {
        let refreshToken = oauth.refresh_token;

        if (refreshToken) {

        }
      }
    }
  },
  restore () {
    if (!this.restoreConfig.enable) {
      return;
    }

    if (sessionStorage.getItem('loaded') && sessionStorage.getItem('sid')) {
      const config = this.restoreConfig;

      if (config) {
        let oauth = JSON.parse(sessionStorage.getItem('oauth'));

        if (oauth) {
          this.restoreOAuth();

          const self = this;
        }
      }
    } else {
      sessionStorage.setItem('loaded', true);
    }
  }
};
